package cn.itsource.org.controller;

import cn.itsource.common.controller.BaseController;
import cn.itsource.common.util.AjaxResult;
import cn.itsource.common.util.ExcelUtils;
import cn.itsource.org.domain.Department;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.dto.DepartmentDto;
import cn.itsource.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(value = "部门的API",description="部门相关的CRUD功能")
@RestController
@RequestMapping("/department")
public class DepartmentController extends BaseController<Department> {

    @Autowired
    private IDepartmentService departmentService;

    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response){
        List<Department> all = departmentService.findAll();
        ExcelUtils.exportExcel(all,"部门数据","部门sheet",
                Department.class,"dept.xls",true,response);
    }

    @PostMapping("/importExcel")
    public void importExcel(@RequestPart("file") MultipartFile file){
        List<Department> list = ExcelUtils.importExcel(file,1,1,Department.class);
        System.out.println("导入数据一共【"+list.size()+"】行");
        for (Department department:list) {
            System.out.println(department);
        }
    }

    /**
     * 新增和修改部门
     * @param departmentDto
     * @return
     */
    @PutMapping("/save")
    @ApiOperation("保存或者修改")
    public AjaxResult save(@RequestBody DepartmentDto departmentDto){
        try{
            departmentService.save(departmentDto);
            return AjaxResult.me().setSuccess(true).setMessage("保存成功");
        }catch (Exception e){
            e.printStackTrace() ;
            return AjaxResult.me().setSuccess(false).setMessage("保存失败");
        }
    }


    @PatchMapping("/queryTree")
    public AjaxResult queryTree(){
        try{

            return AjaxResult.me()
                    .setSuccess(true)
                    .setResultObj(departmentService.queryTree());
        }catch (Exception e){
            e.printStackTrace() ;
            return AjaxResult.me().setSuccess(false).setMessage("查询失败");
        }
    }


}
